package com.cloud.common.bean;

import com.cloud.common.util.ReflectUtils;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.http.HttpStatus;

/**
 * 结果
 */
@Data
@Accessors(chain = true)
public class ResultInfo<T> {
    /**
     * 状态码
     * 200成功
     * 400参数错误
     * 401未经授权
     * 403禁止访问
     * 404请求路径不存在
     * 405请求方法不允许
     * 417执行失败
     * 423熔断限流
     * 429访问频繁
     * 500系统错误
     */
    private int code;

    /**
     * 消息
     */
    private String message;

    /**
     * 数据
     */
    private T data;

    public static <T> ResultInfo<T> success() {
        return new ResultInfo<T>().setCode(HttpStatus.OK.value());
    }

    public static <T> ResultInfo<T> failure() {
        return new ResultInfo<T>().setCode(HttpStatus.EXPECTATION_FAILED.value());
    }

    public static <T> ResultInfo<T> badRequest() {
        return new ResultInfo<T>().setCode(HttpStatus.BAD_REQUEST.value());
    }

    public static <T> ResultInfo<T> manyRequest() {
        return new ResultInfo<T>().setCode(HttpStatus.TOO_MANY_REQUESTS.value());
    }

    public <T> ResultInfo<T> setCode(int code) {
        HttpStatus status = HttpStatus.resolve(code);
        if (status != null) {
            if (status == HttpStatus.BAD_REQUEST) {
                this.message = "参数错误";
            } else if (status == HttpStatus.UNAUTHORIZED) {
                this.message = "未经授权";
            } else if (status == HttpStatus.FORBIDDEN) {
                this.message = "禁止访问";
            } else if (status == HttpStatus.NOT_FOUND) {
                this.message = "请求路径不存在";
            } else if (status == HttpStatus.METHOD_NOT_ALLOWED) {
                this.message = "请求方法不允许";
            } else if (status == HttpStatus.EXPECTATION_FAILED) {
                this.message = "执行失败";
            } else if (status == HttpStatus.LOCKED) {
                this.message = "熔断限流请稍后再试";
            } else if (status == HttpStatus.TOO_MANY_REQUESTS) {
                this.message = "访问频繁请稍后再试";
            } else if (status == HttpStatus.INTERNAL_SERVER_ERROR) {
                this.message = "系统内部错误";
            } else if (status == HttpStatus.NOT_IMPLEMENTED) {
                this.message = "系统升级维护请稍后再试";
            } else {
                this.message = status.getReasonPhrase();
            }
        }
        this.code = code;
        return (ResultInfo<T>) this;
    }

    public <T> ResultInfo<T> setMessage(String message) {
        this.message = message;
        return (ResultInfo<T>) this;
    }

    public <T> ResultInfo<T> setData(T data) {
        // 泛型不能转换，所以使用反射进行设置
        ReflectUtils.setField(this, "data", data);
        return (ResultInfo<T>) this;
    }

    public boolean successful() {
        return this.code == HttpStatus.OK.value();
    }
}